package com.ruitu.mall_98_2.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.CalcUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.TimeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.mine.AddressListActivity;
import com.ruitu.mall_98_2.mvp.contract.ByNowFillInOrderContract;
import com.ruitu.mall_98_2.mvp.model.ByNowFillInOrderModel;
import com.ruitu.mall_98_2.mvp.presenter.ByNowFillInOrderPresenter;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.BuyNow;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.mine.Address;
import com.ruitu.router_module.bean.mine.Coupon;
import com.ruitu.router_module.bean.order.CommitOrder;
import com.ruitu.router_module.bean.order.ConfirOrder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ByNowFillInOrderActivity extends MyBaseActivity<ByNowFillInOrderPresenter, ByNowFillInOrderModel> implements ByNowFillInOrderContract.View {
    private LinearLayout ll_address;
    private LinearLayout ll_order;
    private LinearLayout ll_order_massege;
    private TextView tv_consignee;//收货人
    private TextView tv_tel;//电话
    private TextView tv_address;//地址
    private TextView tv_new_add_address;//新建地址
    private TextView tv_shop_name;//店铺名
    private ImageView iv_order_commodity_img;//商品图
    private TextView tv_commodity_name;//商品名
    private TextView tv_info;//商品信息
    private TextView tv_commodity_price;//商品价钱
    private TextView tv_commodity_num;//数量
    private RelativeLayout rl_coupon;//优惠券
    private TextView tv_coupon;
    private TextView tv_total_postage_price;//快递费
    private EditText et_leave_a_message;//买家留言
    private TextView tv_subtotal_sum;//商品总数量
    private TextView tv_subtotal_price;//商品总价钱
    private TextView tv_postage_all_price;//商品总价钱
    private TextView tv_actually_paid;//商品总价钱
    private TextView tv_end_pay;//尾款
    private TextView tv_send_time;//发货时间
    private TextView tv_commit_order;//提交订单
    private TextView tv_order_pay;//订金

    private ImageView iv_company_logo;
    //    private List<Address> addresses;//地址列表
    private EditText et_buyer_messaage;
    private Address address;
    private List<Integer> skipId = new ArrayList<>();
    String addressId = null;

    private CommitOrder commitOrder;
    private BuyNow buyNow;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
        setHeadTitle("确认订单");
        skipId.add(R.id.header);
        showEmptyView(skipId);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_by_now_fill_in_order;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return findViewById(R.id.progress);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == ll_address) {
            Bundle bundle = new Bundle();
            bundle.putString("from", "from");
            startActivity(AddressListActivity.class, bundle);
        }

        if (v == tv_commit_order) {
            if (address == null) {
                ToastUtils.showShort("请添加收货地址");
                return;
            }
            String userCouponId = null;
            if (commitOrder.getGoods().getCoupon() != null) {
                userCouponId = commitOrder.getGoods().getCoupon().getUserCouponId();
            }
            showProgress();
            mPresenter.buyNowForApp(AppHolder.instance().getUser().getAccountId(), buyNow.getGoodsId(), buyNow.getNum() + "", buyNow.getSkuId(), buyNow.getStatus(), address.getId(), userCouponId);
        }

        if (v == rl_coupon) {
            if (TextUtils.equals(buyNow.getStatus(), "0")) {
                if (commitOrder.getGoods().getCouponStatus().equals("0")) {
                    ToastUtils.showShort("此商品不参加任何优惠");
                } else {
                    showCouponDialog(commitOrder.getCouponList());
                }
            } else {
                ToastUtils.showShort("此商品不参加任何优惠");
            }
        }

    }

    @Override
    protected void initViews() {
        super.initViews();
        buyNow = (BuyNow) getIntent().getExtras().get("buyNow");
        getAddress();
        ll_address = findViewById(R.id.ll_address);
        ll_order = findViewById(R.id.ll_order);
        ll_order_massege = findViewById(R.id.ll_order_massege);
        tv_consignee = findViewById(R.id.tv_consignee);
        tv_tel = findViewById(R.id.tv_tel);
        tv_address = findViewById(R.id.tv_address);
        tv_new_add_address = findViewById(R.id.tv_new_add_address);
        tv_shop_name = findViewById(R.id.tv_shop_name);
        iv_order_commodity_img = findViewById(R.id.iv_order_commodity_img);
        tv_commodity_name = findViewById(R.id.tv_commodity_name);
        tv_info = findViewById(R.id.tv_info);
        tv_commodity_price = findViewById(R.id.tv_commodity_price);
        tv_commodity_num = findViewById(R.id.tv_commodity_num);
        rl_coupon = findViewById(R.id.rl_coupon);
        tv_coupon = findViewById(R.id.tv_coupon);
        tv_total_postage_price = findViewById(R.id.tv_total_postage_price);
        et_leave_a_message = findViewById(R.id.et_leave_a_message);
        tv_subtotal_sum = findViewById(R.id.tv_subtotal_sum);
        tv_subtotal_price = findViewById(R.id.tv_subtotal_price);
        tv_postage_all_price = findViewById(R.id.tv_postage_all_price);
        tv_actually_paid = findViewById(R.id.tv_actually_paid);
        tv_commit_order = findViewById(R.id.tv_commit_order);
        tv_order_pay = findViewById(R.id.tv_order_pay);
        tv_end_pay = findViewById(R.id.tv_end_pay);
        tv_send_time = findViewById(R.id.tv_send_time);
        et_buyer_messaage = findViewById(R.id.et_buyer_messaage);
        iv_company_logo = findViewById(R.id.iv_company_logo);
        setListener();
    }

    @Override
    public void setSuc(CommitOrder commitOrder) {
        this.commitOrder = commitOrder;
        if (commitOrder != null) {
            showContent(null);
            initAddress();
        } else {
            showEmptyView(skipId);
        }
    }

    @Override
    public void setFailed() {
        showError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAddress();
            }
        });
    }

    @Override
    public void setPaySuc(ConfirOrder confirOrder) {
        confirOrder.setStatus(buyNow.getStatus());
        Intent intent = new Intent(this, PayOrderActivity.class);
        intent.putExtra("confirOrder", confirOrder);
        startActivity(intent);
        finish();
    }

    @Override
    public void setListCoupon(List<Coupon> coupon) {
//        showCouponDialog(coupon);
    }

    private int size = 0;

    //初始化数据
    private void initAddress() {
        if (address == null) {
            tv_new_add_address.setVisibility(View.VISIBLE);
        } else {
            tv_new_add_address.setVisibility(View.GONE);
            tv_consignee.setText("收货人:" + address.getName());
//            String new_tel = address.getPhone().substring(0, 3) + "****" + address.getPhone().substring(6, 10);
            String new_tel = address.getPhone();
            tv_tel.setText(new_tel);
            tv_address.setText(address.getProvince() + address.getCity() + address.getCounty() + address.getAddress());
        }
        CommitOrder.Goods goods = commitOrder.getGoods();
        tv_shop_name.setText(goods.getCompanyName());
        Glide.with(this).load(Config.BASE_URL + goods.getCompanyImage()).apply(Arad.opts_shop).into(iv_company_logo);
        Glide.with(this).load(Config.BASE_URL + goods.getImageUrl()).apply(Arad.opts).into(iv_order_commodity_img);

        tv_commodity_name.setText(goods.getGoodName());
        tv_info.setText(goods.getSkuName());
        tv_commodity_price.setText("￥" + goods.getGoodMarket());
        tv_commodity_num.setText("x" + goods.getCartGoodsNum());

        if (!isDataEmpty(commitOrder.getCouponList())) {
            size = commitOrder.getCouponList().size();
        }
        if (TextUtils.equals(buyNow.getStatus(), "0")) {
            if (goods.getCouponStatus().equals("0")) {
                tv_coupon.setText("此商品不参加任何优惠");
            } else {
                tv_coupon.setText("选取优惠券");
            }
        } else {
            tv_coupon.setText("此商品不参加任何优惠");
        }

        if (TextUtils.equals(goods.getGoodPostage(), "0")) {
            tv_total_postage_price.setText("包邮");
        } else {
            tv_total_postage_price.setText(goods.getFreightMoney() + "元");
        }
        if (TextUtils.equals(commitOrder.getStatus(), "1")) {
            ll_order.setVisibility(View.VISIBLE);
            ll_order_massege.setVisibility(View.GONE);
            tv_order_pay.setText(goods.getAdvanceProp() + "元");
            tv_actually_paid.setText("实付款:  " + "￥" + goods.getAdvanceProp());
            tv_end_pay.setText(goods.getTailMoney() + "元");
            tv_send_time.setText("付款后" + goods.getPreSaleDelivey() + "天");
        } else {
            ll_order.setVisibility(View.GONE);
            ll_order_massege.setVisibility(View.VISIBLE);
            tv_actually_paid.setText("实付款:  " + "￥" + goods.getRealMoney());
        }
        tv_subtotal_sum.setText("共" + goods.getCartGoodsNum() + "件商品");
        tv_subtotal_price.setText(goods.getTotalMoney() + "元");


    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 999) {
                Coupon coupon = commitOrder.getGoods().getCoupon();
                if (TextUtils.equals(coupon.getStatus(), "1")) {
                    tv_coupon.setText("优惠" + coupon.getDiscountRatio() + "%");
                } else {
                    tv_coupon.setText("满减" + coupon.getReduceMoney() + "元");
                }
                double total = 0;
                if (coupon.getStatus().equals("1")) {
                    Double multiply = CalcUtils.sub(Double.parseDouble(commitOrder.getGoods().getTotalMoney()), CalcUtils.multiply(Double.parseDouble(commitOrder.getGoods().getTotalMoney()), Double.parseDouble(coupon.getDiscountRatio()) / 100, 2, RoundingMode.HALF_UP));
                    total = CalcUtils.add(total, multiply);
                } else {
                    Double sub = CalcUtils.sub(Double.parseDouble(commitOrder.getGoods().getTotalMoney()), Double.parseDouble(coupon.getReduceMoney()));
                    total = CalcUtils.add(total, sub);
                }
                tv_subtotal_price.setText(total + "元");
                tv_actually_paid.setText("实付款:  " + "￥" + total);
            }
        }

    };

    private void getAddress() {
        final String accountId = AppHolder.instance().getUser().getAccountId();
        APIRetrofit.getDefault().getMineAddress(accountId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult<List<Address>>>() {
                    @Override
                    public void onError(Throwable e) {
                        Logg.i(e.toString());
                        hideProgress();
                        showError(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                getAddress();
                            }
                        });

                    }

                    @Override
                    public void onNext(BaseResult<List<Address>> listBaseResult) {
                        hideProgress();
                        if (listBaseResult.isSuccess()) {
                            if (!isDataEmpty(listBaseResult.getData())) {
                                address = listBaseResult.getData().get(0);

                            }
                            getData(addressId);
                        }
                    }
                });
    }

    /**
     * 优惠券列表
     */
    private void showCouponDialog(List<Coupon> couponList) {
        View view = View.inflate(this, R.layout.item_coupon_dialog, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setContentView(view);
        ImageView iv_close = view.findViewById(R.id.iv_close);
        TextView tv_coupon_redemption_centre = view.findViewById(R.id.tv_coupon_redemption_centre);
        LinearLayout ll_coupon_null = view.findViewById(R.id.ll_coupon_null);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DataAdapter adapter = new DataAdapter(this);
        recyclerView.setAdapter(adapter);
        if (isDataEmpty(couponList)) {
            ll_coupon_null.setVisibility(View.VISIBLE);
        } else {
            adapter.setDataList(couponList);
            ll_coupon_null.setVisibility(View.GONE);
        }

//        tv_coupon_redemption_centre.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                try {
//                    A_Rutils.startActivity(ByNowFillInOrderActivity.this,"com.ruitu.mall_98_1.product.activity.CouponListPlatformActivity");
//                } catch (ClassNotFoundException e) {
//                    e.printStackTrace();
//                }
//            }
//        });

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        //设置背景半透明色
        backgroundAlpha(0.5f);
        //popupWindow  事件监听
        popupWindow.setOnDismissListener(new PopupDismissListener());
        View rootView = LayoutInflater.from(ByNowFillInOrderActivity.this).inflate(R.layout.activity_add_address, null);
        //将PopupWindow置于activity的底部
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);

    }

    class DataAdapter extends ListBaseAdapter<Coupon> {

        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_coupon;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_sum = holder.getView(R.id.tv_sum);
            TextView tv_user_type = holder.getView(R.id.tv_user_type);
            TextView tv_user_restrict = holder.getView(R.id.tv_user_restrict);
            TextView tv_useful_life = holder.getView(R.id.tv_useful_life);
            LinearLayout ll_immediate_use = holder.getView(R.id.ll_immediate_use);
            final Coupon coupon = mDataList.get(position);
            if (TextUtils.equals(coupon.getStatus(), "1")) {
                tv_sum.setText(coupon.getDiscountRatio() + "%");
                tv_user_restrict.setText("企业内商品优惠" + coupon.getDiscountRatio() + "%");
            } else {
                tv_sum.setText("￥" + coupon.getReduceMoney());
                tv_user_restrict.setText("订单金额满" + coupon.getSatisfyMoney() + "元可使用");
            }

            if (TextUtils.equals(coupon.getType(), "1")) {
                tv_user_type.setText("全类商品通用");
            } else {
                if (TextUtils.isEmpty(coupon.getCompanyName())) {
                    if (TextUtils.equals(coupon.getShopType(), "1")) {
                        tv_user_type.setText(coupon.getGoodsName());
                    } else {
                        tv_user_type.setText(coupon.getCompanyName());
                    }
                } else {
                    tv_user_type.setText(coupon.getCompanyName());
                }
            }

            tv_useful_life.setText("有效期:" + TimeUtils.millis2String(Long.parseLong(coupon.getCreateTime()), new SimpleDateFormat("yyyy-MM-dd")) + " " + TimeUtils.millis2String(Long.parseLong(coupon.getUseTime()), new SimpleDateFormat("yyyy-MM-dd")));

            ll_immediate_use.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    commitOrder.getGoods().setCoupon(coupon);
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                    handler.sendEmptyMessage(999);
                }
            });
        }
    }

    class PopupDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    private void backgroundAlpha(float v) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = v;
        getWindow().setAttributes(layoutParams);
    }

    /**
     * 选取收货地址
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setAddresses(EventModel<Address> addresses) {
        if (addresses.getEventCode() == 18111600) {
            this.address = addresses.getEventObj();
            getData(address.getId());
        }
    }

    public void getData(String adId) {
        showProgress();
        mPresenter.buyNowForSettlement(AppHolder.instance().getUser().getAccountId(), buyNow.getGoodsId(), buyNow.getNum() + "", buyNow.getSkuId(), buyNow.getStatus(), adId);
    }

    private void setListener() {
        ll_address.setOnClickListener(this);
        tv_commit_order.setOnClickListener(this);
        rl_coupon.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }
}
